package mobi.hami.huapin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import mobi.hami.huapin.core.stock.StockUtil;
import mobi.hami.huapin.dao.ProductskuMapper;
import mobi.hami.huapin.dto.HuaPinOutPutDTO;
import mobi.hami.huapin.dto.HuaPinParamDTO;
import mobi.hami.huapin.dto.UserOrderDTO;
import mobi.hami.huapin.model.*;
import mobi.hami.huapin.service.*;
import mobi.hami.huapin.util.BeanUtil;
import mobi.hami.huapin.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.xml.ws.soap.AddressingFeature;
import java.text.SimpleDateFormat;
import java.time.DateTimeException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Create by 小峰 on 2018/9/1.
 */
@Service
public class HuapinOrderServiceImpl implements HuapinOrderService {

    @Autowired
    private HuaPinService huaPinService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserConsigneeService userConsigneeService;
    @Autowired
    private UserOrderDetailService userOrderDetailService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private ProductskuMapper productskuMapper;
    @Autowired
    private StockUtil stockUtil;


    /**
     * 根据地址id　获取该地址下所有拼团的信息
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> getListByAddressId(Map<String, Object> map) {

        Integer addressId=0;
        Integer pageIndex = 1;
        Integer pageSize = 10;
        if (null != map && !map.isEmpty()) {
            addressId = map.get("addressId") == null ? 0 : Integer.parseInt(map.get("addressId").toString());
            pageIndex = map.get("pageIndex") == null ? 1 : Integer.parseInt(map.get("pageIndex").toString());
            pageIndex = pageIndex == 0 ? 1 : pageIndex;
            pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
            pageSize = pageSize == 0 ? 10 : pageSize;
        }

        if(addressId==null || addressId<=0)
            return new HashMap<>();
        Page page = PageHelper.startPage(pageIndex, pageSize, true).reasonable(true);
        List<HuaPin> huaPinList = huaPinService.selectListByAddressId(addressId);
        if(huaPinList==null || huaPinList.size()<=0)
            return new HashMap<>();
        Collections.sort(huaPinList,Comparator.comparing(HuaPin::getId).reversed());
        List<HuaPinOutPutDTO> huaPinOutPutDTOList = new ArrayList<>();
        for (HuaPin huapin : huaPinList) {
            huaPinOutPutDTOList.add(createHuaPinOutPutDTO(huapin));
        }
        return BeanUtil.ResultResponseMap(page, huaPinOutPutDTOList, pageSize, pageIndex);
    }

    /**
     * 根据用户Id　获取该用户所有拼团信息
     *
     * @param map
     * @return
     */
    @Override
    public  Map<String, Object> getListByUserId(Map<String, Object> map) {

        Integer userId=0;
        Integer pageIndex = 1;
        Integer pageSize = 10;
        if (null != map && !map.isEmpty()) {
            userId = map.get("userId") == null ? 0 : Integer.parseInt(map.get("userId").toString());
            pageIndex = map.get("pageIndex") == null ? 1 : Integer.parseInt(map.get("pageIndex").toString());
            pageIndex = pageIndex == 0 ? 1 : pageIndex;
            pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
            pageSize = pageSize == 0 ? 10 : pageSize;
        }
        if(userId==null || userId<=0)
            return new HashMap<>();
        List<HuaPinOutPutDTO> huaPinOutPutDTOList = new ArrayList<>();
        Page page = PageHelper.startPage(pageIndex, pageSize, true).reasonable(true);
        List<UserOrderDTO> userOrderDTOList = userOrderService.getListByUserId(userId);
        if (userOrderDTOList != null && userOrderDTOList.size()>0) {
            userOrderDTOList = userOrderDTOList.stream()
                    .filter(m -> m.getOrder_status() != 1)
                    .collect(Collectors.toList());
            Collections.sort(userOrderDTOList,Comparator.comparing(UserOrderDTO::getId).reversed());
        }else{
            return new HashMap<>();
        }
        for (UserOrderDTO userOrderDTO : userOrderDTOList) {
            HuaPin huapin = huaPinService.selectOnbyId(userOrderDTO.getHuapin_id());
            huaPinOutPutDTOList.add(createHuaPinOutPutDTO(huapin));
        }
        return BeanUtil.ResultResponseMap(page, huaPinOutPutDTOList, pageSize, pageIndex);
    }

    /**
     * 根据花拼Id 获取该拼团的所有定单信息
     *
     * @param id
     * @return
     */
    @Override
    public HuaPinOutPutDTO getOneByHuapinId(Integer id) {
        return createHuaPinOutPutDTO(huaPinService.selectOnbyId(id));
    }

    /**
     * 根据花拼Id 获取该拼团的所有定单信息 用于打印
     *
     * @param id
     * @return
     */
    @Override
    public HuaPinOutPutDTO getOneForPrint(Integer id) {
        return createHuaPinOutPutDTOForPrint(huaPinService.selectOnbyId(id));
    }

    private HuaPinOutPutDTO createHuaPinOutPutDTOForPrint(HuaPin huaPin) {
        HuaPinOutPutDTO huaPinOutPutDTO = new HuaPinOutPutDTO();
        huaPinOutPutDTO.setUserOrderOutList(new ArrayList<>());
        huaPinOutPutDTO.setHuaPin(huaPin);
        List<UserOrderDTO> userOrderDTOList = userOrderService.getListByHuapnId(huaPin.getId());
        for (UserOrderDTO userOrderDTO : userOrderDTOList) {

            if (userOrderDTO.getUser_id() == huaPin.getUser_id()) {
                if (userOrderDTO.getOrder_status() > 2) {
                    huaPin.setStatus(userOrderDTO.getOrder_status());
                }
            }
            userOrderDTO = userOrderDTOPropertyValue(userOrderDTO);
            List<UserOrderDetail> userOrderDetails = userOrderDetailService.getListByOrderIdAll(userOrderDTO.getId());

            StringBuilder skuids = new StringBuilder();
            userOrderDetails.forEach(a->{
                skuids.append(a.getSku_id()+",");
            });

            if (skuids.toString().length() >0)
            {
                String ids = skuids.toString().substring(0,skuids.toString().length() -1);
                List<Productsku> productskus = productskuMapper.getListForPrint(ids);


                userOrderDetails.forEach(a->{

                    Optional<Productsku> sku = productskus.stream().filter(b-> a.getSku_id() == b.getId()).findFirst();
                    if (sku.isPresent())
                    {
                        a.setSku_photo(sku.get().getBarcode());
                    }
                    else
                    {
                        a.setSku_photo("");
                    }

                });

            }






            huaPinOutPutDTO.userHuapinAdd(userOrderDTO, userOrderDetails);
        }
        return huaPinOutPutDTO;
    }

    /**
     * 保存花拼　订单信息
     *
     * @param huaPinParamDTO
     * @return 返回订单Id
     */
    @Override
    public Map<String, String> saveHuaPinOrder(HuaPinParamDTO huaPinParamDTO) throws Exception {
        UserOrder userOrder = new UserOrder();
        BeanUtil.copyProperties(huaPinParamDTO, userOrder);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

        userOrder.setOrder_code(simpleDateFormat.format(Calendar.getInstance().getTime()) + huaPinParamDTO.getUser_id());

        //扣库存
        String subresult =stockUtil.subBat(huaPinParamDTO.getUserOrderDetailList(), userOrder.getOrder_code(),"");
        if (!subresult.equals("0"))
        {
            Map<String, String> map = new HashMap();
            map.put("huapin_Id", "0");
            map.put("order_Id", "0");
            map.put("order_code", "0");
            map.put("sku",subresult );
            return map;
        }

        //保存花拼信息
        if (huaPinParamDTO.getHuapin_id() <= 0) {
            HuaPin huaPin = new HuaPin();
            BeanUtil.copyProperties(huaPinParamDTO, huaPin);
            huaPin.setId(huaPinParamDTO.getHuapin_id());
            Calendar now = Calendar.getInstance();
            huaPin.setBegin_time(now.getTime());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDat = sdf.format(now.getTime()) + " 16:00:00";

            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date endOrder = sdf.parse(strDat);

            if (endOrder.before(new Date())) {
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(endOrder);
                calendar.add(Calendar.DATE, 1);//把日期往后增加一天.正数往后推,负数往前推
                endOrder = calendar.getTime();   //这个时间就是日期往后推一天的结果
            }
            huaPin.setEnd_time(endOrder);
            huaPin.setHp_code("HP"+simpleDateFormat.format(Calendar.getInstance().getTime())+new Random().nextInt(1000));
            huaPin.setStatus(1);
            huaPinService.save(huaPin);
            huaPinParamDTO.setHuapin_id(huaPin.getId());
            userOrder.setHuapin_role(1);
        } else {
            userOrder.setHuapin_role(2);
        }

        //用户订单处理
        userOrder.setOrder_status(1);
        userOrder.setHuapin_id(huaPinParamDTO.getHuapin_id());


        userOrder.setSku_count(huaPinParamDTO.getUserOrderDetailList().stream().mapToInt(m -> m.getSku_cout()).sum());
        userOrderService.saveModel(userOrder);

        //如果有优惠券Id，则更新优惠券信息
        if (huaPinParamDTO.getCoupon_id() > 0) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setId(huaPinParamDTO.getCoupon_id());
            userCoupon.setIs_valid(2);
            userCouponService.update(userCoupon);
        }

        userOrderDetailService.addList(huaPinParamDTO.getUserOrderDetailList(), userOrder.getId());

        Map<String, String> map = new HashMap();
        map.put("huapin_Id", huaPinParamDTO.getHuapin_id().toString());
        map.put("order_Id", userOrder.getId().toString());
        map.put("order_code", userOrder.getOrder_code());
        return map;
    }


    private HuaPinOutPutDTO createHuaPinOutPutDTO(HuaPin huaPin) {
        HuaPinOutPutDTO huaPinOutPutDTO = new HuaPinOutPutDTO();
        huaPinOutPutDTO.setUserOrderOutList(new ArrayList<>());
        huaPinOutPutDTO.setHuaPin(huaPin);
        List<UserOrderDTO> userOrderDTOList = userOrderService.getListByHuapnId(huaPin.getId());
        for (UserOrderDTO userOrderDTO : userOrderDTOList) {

            if (userOrderDTO.getUser_id() == huaPin.getUser_id()) {
                if (userOrderDTO.getOrder_status() > 2) {
                    huaPin.setStatus(userOrderDTO.getOrder_status());
                }
            }
            userOrderDTO = userOrderDTOPropertyValue(userOrderDTO);
            List<UserOrderDetail> userOrderDetails = userOrderDetailService.getListByOrderId(userOrderDTO.getId());
            huaPinOutPutDTO.userHuapinAdd(userOrderDTO, userOrderDetails);
        }
        return huaPinOutPutDTO;
    }

    /**
     * 匹配用户信息及配送人信息
     *
     * @param userOrderDTO
     * @return
     */
    private UserOrderDTO userOrderDTOPropertyValue(UserOrderDTO userOrderDTO) {
        if (userOrderDTO != null) {
            UserInfo userInfo = userInfoService.selectOnebyId(userOrderDTO.getUser_id());
            if (userInfo != null) {
                userOrderDTO.setUser_name(userInfo.getNick_name());
                userOrderDTO.setHead_photo(userInfo.getHead_photo());
            }

            UserConsignee userConsignee = userConsigneeService.selectOnById(userOrderDTO.getConsignee_id());
            if (userConsignee != null) {
                userOrderDTO.setConsignee_name(userConsignee.getName());
                userOrderDTO.setConsigee_phone(userConsignee.getPhone());
            }
        }
        return userOrderDTO;
    }
}
